
<template>

  <div>
    <a-button type="primary" @click="showModal">Add</a-button>
    <a-modal v-model:open="open" title="Title" :confirm-loading="confirmLoading" @ok="handleOk">
      <!--      <p>{{ modalText }}</p>-->
      <a-form
          :model="cityformState"
          name="city"
          :label-col="{ span: 8 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
      >
        <!--todo 这里name 和formState需要修改-->
        <a-form-item
            label="省份"
            name="province"
            :rules="[{ required: true, message: '请输入省份名！' }]"
        >
          <a-input v-model:value="cityformState.province"/>
        </a-form-item>
        <a-form-item
            label="城市名"
            name="city"
            :rules="[{ required: true, message: '请输入城市名！' }]"
        >
          <a-input v-model:value="cityformState.city"/>
        </a-form-item>
        <a-form-item
            label="城市编号"
            name="city"
            :rules="[{ required: true, message: '请输入城市编号！' }]"
        >
          <a-input v-model:value="cityformState.cityNumber"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>

  <!--todo 改成动态加载数据-->
  <a-table :columns="columns" :data-source="dataSource" bordered>
    <template #bodyCell="{ column, text, record }">
      <template
          v-if="
          ['province', 'city', 'cityNumber'].includes(
            column.dataIndex
          )
        "
      >
        <div>
          <a-input
              v-if="editableData[record.key]"
              v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.key]">
            <a-typography-link @click="save(record.key)"
            >Save</a-typography-link
            >
            <a-popconfirm title="Sure to cancel?" @confirm="cancel(record.key)">
              <a>Cancel</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.key)">Edit</a>
          </span>
          <a-popconfirm
              v-if="dataSource.length"
              title="Sure to delete?"
              @confirm="onDelete(record.key)"
          >
            <a>Delete</a>
          </a-popconfirm>
        </div>
      </template>
    </template>
  </a-table>
</template>

<script setup>
import {cloneDeep} from "lodash-es";
import {onMounted, reactive, ref} from "vue";
import myAxios from "../plugins/myAxios.js";

const columns = [
  {
    title: "省份",
    dataIndex: "province",
    // width: "25%",
  },
  {
    title: "城市名",
    dataIndex: "city",
    // width: "15%",
  },
  {
    title: "城市编号",
    dataIndex: "cityNumber",
  },
  {
    title: "创建时间",
    dataIndex: "createtime",
  },
  {
    title: "更新时间",
    dataIndex: "updatetime",
  },

  {
    title: "operation",
    dataIndex: "operation",
  },
];
const data = ref([])
onMounted(async () => {
  const res = await myAxios({
    method: "get",
    url: "/city/list/city",
  })
  console.log(res, "mounted")

  data.value = res.data.records
  // 这里是给数组加上key=id，key是表格用来区分每条数据的
  data.value.filter((item) => {
    item.key = item.cityId;
    // console.log(item,"item")
  })
  console.log(res.data.records, "mounted")

  // console.log(data.value, "myData")
})

const dataSource = ref(data);
const editableData = reactive({});
// todo 修改
const edit = (key) => {
  editableData[key] = cloneDeep(
      dataSource.value.filter((item) => key === item.key)[0]
  );
  console.log(editableData[key]);
};
//这里是修改数组保存的逻辑 和后端有不匹配的地方在这里修改一下
const save = async (key) => {
  Object.assign(
      dataSource.value.filter((item) => key === item.key)[0],
      editableData[key]
  );
  // 这里发现data 和 dataSource 修改的那条数据都改变了
  const updateDataSource = dataSource.value.filter((item) => key === item.key)[0]

  const res = await myAxios({
    method: "post",
    url: "/city/update",
    data: {
      "cityId": updateDataSource.cityId,
      "province": updateDataSource.province,
      "city": updateDataSource.city,
    }
  })
  console.log(res, "edit save")
  delete editableData[key];
};
const cancel = (key) => {
  delete editableData[key];
};

// todo 删除
const onDelete = (key) => {

  let delId;
  const delCity = dataSource.value.filter((item) => {
    if (item.key === key) {
      delId = item.cityId
    }
  });

  const res = myAxios({
    method: "post",
    url: "/city/delete",
    data: {
      "cityId": delId,
    }
  })
  dataSource.value = dataSource.value.filter((item) => item.key !== key);
  console.log(res, delId, delAccountId)

};
// todo 增加

const modalText = ref('Content of the modal');
const open = ref(false);
const confirmLoading = ref(false);
const showModal = () => {
  open.value = true;
};
// 提交表单
const handleOk = async () => {

  await onFinish()
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 2000);
  location.reload();
};

const cityformState = reactive({
  cityId: 0,
  cityNumber: '',
  province: '',
  city: '',
  createtime: '',
  updatetime: '',

});

const onFinish = async (values) => {
  const res = await myAxios({
    method: "post",
    url: "/city/add",
    data: cityformState
  })
  console.log('Success:', values, cityformState);


};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};

</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
